package vip.redme.memory.controller.base;

import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import vip.redme.memory.exception.BizException;
import vip.redme.memory.response.BaseResultCode;
import vip.redme.memory.response.Result;

import static java.util.stream.Collectors.joining;

/**
 * GlobalExceptionHandler
 *
 * @author HUZHAOYANG
 * @version 1.0
 * @date 2021/4/22 14:18
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Result handleException(Exception e) {
        log.error("Exception ------------------> ", e);
        return Result.fail();
    }

    @ExceptionHandler({BindException.class})
    @ResponseBody
    public Result handleException(BindException e) {
        log.error("BindException ------------------> ", e);
        return Result.of(BaseResultCode.FAIL.getCode(),
                e.getFieldErrors().stream()
                 .map(DefaultMessageSourceResolvable::getDefaultMessage)
                 .collect(joining("，")));
    }

    @ExceptionHandler({BizException.class})
    @ResponseBody
    public Result handleException(BizException e) {
        log.error("BizException ------------------> ", e);
        return Result.of(e.getCode(), e.getMessage());
    }

    @ExceptionHandler({DataIntegrityViolationException.class})
    @ResponseBody
    public Result handleException(DataIntegrityViolationException e) {
        log.error("DataAccessException ------------------> ", e);
        return Result.of(BaseResultCode.FAIL.getCode(), ExceptionUtil.getRootCauseMessage(e));
    }
}
